package com.ruoyi.common.utils;

import com.ruoyi.framework.config.RuoYiConfig;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

public class ImageUtils {

    public static void Base64ToImage(String base64String, String fileName) {
        String filePath = RuoYiConfig.getUploadPath() + "/faceAuth/";
        try {
            File f = new File(filePath);
            if (!f.exists()) {
                f.mkdirs();
            }
            // 解码Base64字符串为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64String);
            // 将字节数组转换为图片
            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            BufferedImage image = ImageIO.read(bis);
            // 保存图片

            File outputFile = new File(filePath + fileName);
            ImageIO.write(image, "png", outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String convertToBase64(byte[] imageBytes) {
        String base64Image = "";
        try {
            base64Image = Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64Image;
    }

}
